package com.inspur.demo.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

/**
 * 自定义前置拦截器
 */
@Component
public class CustomerPostFilter extends ZuulFilter {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public String filterType() {
        return "post";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        logger.info("--> CustomerPostFilter <--");
        RequestContext ctx = RequestContext.getCurrentContext();
        int responseStatusCode = ctx.getResponseStatusCode();
        String responseBody = ctx.getResponseBody();
        logger.info("responseStatusCode:" + responseStatusCode);
        logger.info("responseBody:" + responseBody);
        Object object = ctx.get("token");
        logger.info("token:" + object);
        InputStream responseDataStream = ctx.getResponseDataStream();
        try {
            if (responseDataStream != null) {
                ByteArrayOutputStream result = new ByteArrayOutputStream();
                byte[] buffer = new byte[1024];
                int length;
                while ((length = responseDataStream.read(buffer)) != -1) {
                    result.write(buffer, 0, length);
                }
                String str = result.toString(StandardCharsets.UTF_8.name());
                logger.info("readLines" + str);
                ctx.setResponseBody(str);
            }
        } catch (IOException e) {
            logger.error("CustomerPostFilter 错误", e);
        }
        return null;
    }
}
